package com.smp.controller;

import com.smp.domain.DelayJobEntity;
import com.smp.service.DelayJobService;
import com.smp.support.execute.ExecuteJobImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: xiaoyu
 * @date: 2020/4/23 ,9:37
 * @version: v1.0
 * @description:
 **/
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisDelayController {

    @Autowired
    private DelayJobService delayJobService;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");

    @GetMapping("/delay")
    public Result buildDelayJob(@RequestParam(value = "time") String time) {
        DelayJobEntity delayJob = new DelayJobEntity();
        ExecuteJobImpl executerJob = new ExecuteJobImpl();
        Map<String, String> params = new HashMap<>(1);
        String msg = "这是" + time + "秒的任务";
        params.put("key", msg);
        delayJob.setJobParams(params);
        delayJob.setAClass(executerJob.getClass());
        Date date = new Date();
        log.info("{} 消息的开始时间 >>>> {}", msg, sdf.format(date));
        delayJobService.submitJob(delayJob, Long.valueOf(time), TimeUnit.SECONDS);
        return new Result().success();
    }

    @Data
    class Result {

        private Integer errorCode;

        private String meg;

        private Object data;

        public Result() {
        }

        public Result(Integer errorCode, String meg, Object data) {
            this.errorCode = errorCode;
            this.meg = meg;
            this.data = data;
        }

        public Result success() {
            return new Result(200, null, null);
        }

        public Result success(Object data) {
            return new Result(200, null, data);
        }

        public Result error() {
            return new Result(500, null, null);
        }
    }

}
